home *** CD-ROM | disk | FTP | other *** search
/ Windows News 2010 Summer - Disc 1 / WN_Ete2010_CD1.iso / Onglet5 / Weezo / Weezo setup.exe / {code_appDir} / www / includes / uploadWindow.php < prev    next >
PHP Script  |  2010-05-19  |  18KB  |  427 lines

  1. <?php
  2. /**
  3.  * File upload script, executed in a popup window
  4.  * 2 Steps upload :
  5.  * - 1st step : display "upload in progress" windows, create upload in upload.txt text file, and call doUploadFile JavaScript in opener window
  6.  * - 2nd step : doUploadFile script submits file upload form in pop-up window
  7.  *
  8.  * Display "please wait" screen
  9.  * Upload a file to server, and check authorizations
  10.  *
  11.  * If no file is sent, display "please wait" screen and call doUploadFile script in opener window
  12.  * This script submit file send form, targeting current widows
  13.  * file reception is then detected.
  14.  *
  15.  * PHP version 5
  16.  *
  17.  * LICENSE: This source file is subject to version 3.0 of the PHP license
  18.  * that is available through the world-wide-web at the following URI:
  19.  * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
  20.  * the PHP License and are unable to obtain it through the web, please
  21.  * send a note to license@php.net so we can mail you a copy immediately.
  22.  *
  23.  * @category   NA
  24.  * @package    NA
  25.  * @author     Nicolas Bruley / Peer 2 World <contact@weezo.net>
  26.  * @copyright  2005-2009 Nicolas Bruley / Peer 2 World
  27.  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
  28.  * @version    CVS: $Id:$
  29.  * @link       http://www.weezo.net
  30.  * @since      File available since Release 1.0.0
  31.  */
  32. require_once(INCLUDE_DIR.'outputFunctions.php');
  33. require_once(INCLUDE_DIR.'transferFunctions.php');
  34. require_once(INCLUDE_DIR.'explorerFunctions.php');
  35.  
  36.  
  37. /**
  38.  * @desc : display Upload In Progress (or error) page (main upload page)
  39.  *
  40.  */
  41. function displayUploadInProgressPage(){
  42.     // Set close URL back to resource for frameless display
  43.     $_ENV['winCloseURL']='/res/'.cfRGetVar('type').'/'.cfRGetVar('subType').'/'.cfRGetVar('baseFile');
  44.  
  45.     $message=cfCaption('uploadInProgress',basename($_POST['preUlFile']))."\n".cfCaption('genWait');
  46.  
  47.     // Add upload to transfers list
  48.     if(cfRGetVar('trackTransfers')){
  49.         if(!$tr=tAddUpload(cfUTF8Decode($_POST['preUlDir']), cfUTF8Decode(basename($_POST['preUlFile'])))) {
  50.             $message=cfCaption('genError');
  51.             $error=1;
  52.         }
  53.     }
  54.  
  55.     // Async request (mobile)
  56.     if(cfIsAsync()){
  57.         cfAsyncHeader();
  58.         // Proceed to uploadForm submission
  59.         if(!isset($error)) echo cfAsyncXMLJSaction('doUploadFile("'.((isset($tr))?$tr->id:'').'")');
  60.         // or display error message
  61.         else echo cfAsyncXMLJSaction('initUploadProceed("forbidden","'.$message.'")');
  62.         die(cfAsyncFooter());
  63.     }
  64.  
  65.     // Display page
  66.     cfInsertHEAD(false);
  67. ?>
  68. </head>
  69. <?php
  70.     if(!cfRGetVar('trackTransfers') || (cfRGetVar('trackTransfers') && $tr)) {
  71.         if(isset($tr)) $transferId=$tr->id; else $transferId=rand();
  72.         // On page loaded, call upload javascript funtion in opener window
  73.         if(cfHGetVar('noPopup')) $opener='parent.frames[parent.dgi(winMe.getOpenerId()+\'_if\').name]';    else $opener='opener';
  74.         echo '<body onload="'.$opener.'.doUploadFile(\''.$transferId.'\')">';
  75.     }
  76.     else echo '<body>';
  77.     echo outDivFrame('frame1','id="frame1"').'<div class="frame1header">'.cfCaption('genFileUpload').'</div>';
  78.     // Upload message
  79.     echo '<br/><br/><center>'.$message."<br/><br/>\n";
  80.     // Progress bar iframe
  81.     if(isset($transferId)) echo '<iframe id="uploadProgressIFrame" src="upload.php?progressBar=1&transferId='.$transferId.'" width="80%" height="17" frameborder="0" scrolling="no"></iframe>';
  82.     else echo '<br/>';
  83.     echo "</center><br/><br/>\n";
  84.     insertCloseOnCompletedControl();
  85. ?>
  86. </div>
  87. <script type="text/javascript">
  88. winMe.closeable(false);
  89. winMe.reloadable(false);
  90. winMe.resizeInnerTo(<?php echo (cfGetBrowser()=='gecko')?600:350; // Gecko pb ?>,dgi('frame1').offsetHeight*1+10*actualOffsetTop(dgi('frame1')),1)
  91. </script>
  92. </body>
  93. </html>
  94. <?php
  95.     exit;
  96. }
  97.  
  98. /**
  99.  * @desc Insert control needed for toggleing close transfer on upload completed
  100.  *
  101.  */
  102. function insertCloseOnCompletedControl(){
  103.     echo '<form id="testForm" name="testForm" action="'.$_SERVER['PHP_SELF'].'">';
  104.     echo '<input type="checkbox" '.((cfRGetVar('transferCloseOnCompleted'))?'checked="checked"':'').' onclick="dgn(\'toggleTransferCloseOnCompleted\').value=this.checked;asyncSubmitForm(\'testForm\',true)"><input name="toggleTransferCloseOnCompleted" type="text" style="display:none"/>  ';
  105.     echo cfCaption('transferCloseOnFinish');
  106.     echo '</form>';
  107. }
  108.  
  109. /**
  110.  * @desc : display Upload Completed page
  111.  *
  112.  * @param string $errorMessage
  113.  */
  114. function displayUploadCompletedPage($uploadFile=false,$errorMessage=false){
  115.     /**
  116.      * Mobile devices
  117.      */
  118.     if(cfIsMobile()){
  119.         require_once(INCLUDE_DIR.'mobileFunctions.php');
  120.         mfInsertHead(array('context'=>'view'));
  121.         echo outDivFrame('frame1').'<div class="frame1header">'.cfCaption('genFileUpload').'</div><center>';
  122.  
  123.         // If transfered file is an image, display a thumbnail
  124.         if(efFileType($uploadFile)=='image') $isImage=true; else $isImage=false;
  125.         if(!$errorMessage && $isImage) {
  126.             if(cfRGetVar('path') && cfIsSubDir(cfRGetVar('path'),$uploadFile)) $uploadFileExtPath=cfResourceRelativePath($uploadFile);
  127.             elseif (cfIsSubDir(cfAppResourceDir(),$uploadFile)) $uploadFileExtPath=cfResourceDataDirRelativePath($uploadFile);
  128.             else $uploadFileExtPath=$uploadFile;
  129.             echo '<img src="'.cfExtImage($uploadFileExtPath,80,80,false).'" height="80" alt=""><br/>';
  130.         }
  131.         else echo "<br/><br/>\n";
  132.  
  133.         // Message
  134.         if($errorMessage) echo $errorMessage;
  135.         else echo cfCaption('transfersFinished');
  136.         if(!$isImage) echo "<br/>\n";
  137.         echo '<br/><br/></center></div></body></html>';
  138.         exit;
  139.     }
  140.  
  141.  
  142.  
  143.     // Flash upload: don't display HTML page
  144.     if(isset($_POST['flashUpload'])){
  145.         if(!$uploadFile) cfHTTPError(403);
  146.         exit;
  147.     }
  148.     // Set close URL back to resource for frameless display
  149.     $_ENV['winCloseURL']='/res/'.cfRGetVar('type').'/'.cfRGetVar('subType').'/'.cfRGetVar('baseFile');
  150.  
  151.     // Display page
  152.     cfInsertHEAD(false);
  153.     ?>
  154. <script language="javascript">
  155. function keyPressed(e) {
  156.    if (e.keyCode) keycode=e.keyCode; else keycode=e.which;
  157.    if(keycode==27) winMe.closeMe();
  158. }
  159. winMe.closeable(true);
  160. winMe.reloadable(false);
  161. </script>
  162. </head>
  163. <body <?php
  164.     if(isset($_POST['ulAckJSFunction'])){
  165.         echo 'onload="';
  166.         // If parent window/frame exists, inform parent that upload is finished
  167.         if(cfTGetVar('frames')){
  168.             if(cfHGetVar('noPopup')) $opener='parent.frames[parent.dgi(winMe.getOpenerId()+\'_if\').name]';
  169.             else $opener='opener';
  170.  
  171.             echo $opener.'.'.$_POST['ulAckJSFunction'].'('.(($errorMessage)?'false':'true').');';
  172.         }
  173.         if(!$errorMessage && cfRGetVar('transferCloseOnCompleted')) echo 'winMe.closeMe();';
  174.         echo '"';
  175.     }
  176.     echo ' onKeyPress="keyPressed(event);">';
  177.     echo outDivFrame('frame1').'<div class="frame1header">'.cfCaption('genFileUpload').'</div>';
  178.     echo '<center>';
  179.     if(efFileType($uploadFile)=='image') $isImage=true; else $isImage=false;
  180.     // If transfered file is an image, display a thumbnail
  181.     if(!$errorMessage && $isImage) {
  182.         if(cfRGetVar('path') && cfIsSubDir(cfRGetVar('path'),$uploadFile)) $uploadFileExtPath=cfResourceRelativePath($uploadFile);
  183.         elseif (cfIsSubDir(cfAppResourceDir(),$uploadFile)) $uploadFileExtPath=cfResourceDataDirRelativePath($uploadFile);
  184.         else $uploadFileExtPath=$uploadFile;
  185.         echo '<img src="'.cfExtImage($uploadFileExtPath,80,80,false).'" height="80" alt=""><br/>';
  186.     }
  187.     else echo "<br/><br/>\n";
  188.  
  189.     // Message
  190.     if($errorMessage) echo $errorMessage;
  191.     else echo cfCaption('transfersFinished');
  192.     if(!$isImage) echo "<br/>\n";
  193.  
  194.     // Close button
  195.     echo '<br/>'.outButton(cfCaption('genClose'),"javascript:winMe.closeMe()",outIcon('close'));
  196.     echo '</center>';
  197.     if($errorMessage || !$isImage) echo '<br/><br/>';
  198.     insertCloseOnCompletedControl();
  199.     echo '</div>';
  200.     echo '</body></html>';
  201.  
  202.     // Remove temporary file
  203.     if(isset($_FILES['ulInput']['tmp_name']) && file_exists($_FILES['ulInput']['tmp_name'])) @unlink($_FILES['ulInput']['tmp_name']);
  204.  
  205.     exit();
  206. }
  207.  
  208. /**
  209.  * @desc default uploaded file processing
  210.  *
  211.  */
  212. function uploadProcessUploadedFile(){
  213.     global $transfersArray;
  214.  
  215.     // Prepare to move uploaded file to resource directory
  216.     $uploadDir=str_replace('*resourceBasePath*',cfRGetVar('path'),cfUTF8Decode($_POST['ulDir']));
  217.  
  218.     //$uploadFile=cfJoinPathFile($uploadDir, basename(cfUTF8Decode($_FILES['ulInput']['name'])));
  219.     $uploadFile=cfJoinPathFile($uploadDir, cfUTF8Decode(basename($_POST['postUlFile'])));
  220.  
  221.     // Check destination directory access rights
  222.     if(!cfFileRights($uploadDir,'upload')) displayUploadCompletedPage(false,$uploadDir.cfCaption('explorerErrorFileSend2').' (UL NA)');
  223.  
  224.     // If resource sets an extension filter, verify that file matches
  225.     if(cfRGetVar('extensionFilter') && !in_array(cfFileExtension($uploadFile),cfRGetVar('extensionFilter'))) displayUploadCompletedPage(false,cfCaption('explorerFormatError').' (ext2)');
  226.  
  227.     // If resource sets an file type filter, verify that file matches
  228.     if(cfRGetVar('fileTypeFilter') && !in_array(efFileType($uploadFile),cfRGetVar('fileTypeFilter'))) displayUploadCompletedPage(false,cfCaption('explorerFormatError')).' (filter2)';
  229.  
  230.     // User may write in destination dir
  231.     else {
  232.         if(file_exists($uploadFile) && !cfFileRights($uploadFile,'modify'))  displayUploadCompletedPage(false,cfCaption('explorerErrorFileSend2').' (modify not allowed)');
  233.         else {
  234.             if(file_exists($uploadFile)) {
  235.                 if(cfFileRights($uploadFile,'modify')){
  236.                     if(!customSendToRecycled($uploadFile))  displayUploadCompletedPage(false,cfCaption('explorerErrorFileSend2').' (err deleting prev file)');
  237.                 }
  238.                 else displayUploadCompletedPage(false,cfCaption('explorerErrorFileSend2').' (modify not allowed2)');
  239.             }
  240.  
  241.             // Folder is write-allowed => move uploaded file to folder
  242.             if(@move_uploaded_file($_FILES['ulInput']['tmp_name'], $uploadFile)){
  243.                 // Transfers tracking : set upload as finished
  244.                 if(cfRGetVar('trackTransfers')){
  245.                     $transfersArray[$_POST['ulTransferId']]->status=4;
  246.                     $transfersArray[$_POST['ulTransferId']]->progress=1;
  247.                     // Save result in uploads file
  248.                     tWritePHPTransfersFile($transfersArray);
  249.                 }
  250.                 // Remove temporary file
  251.                 if(isset($_FILES['ulInput']['tmp_name']) && file_exists($_FILES['ulInput']['tmp_name'])) @unlink($_FILES['ulInput']['tmp_name']);
  252.             }
  253.             else{
  254.                 // Remove temporary file
  255.                 if(isset($_FILES['ulInput']['tmp_name']) && file_exists($_FILES['ulInput']['tmp_name'])) @unlink($_FILES['ulInput']['tmp_name']);
  256.                 // Transfers tracking : set upload as failed
  257.                 if(cfRGetVar('trackTransfers')){
  258.                     $transfersArray[$_POST['ulTransferId']]->status=8;
  259.                     $transfersArray[$_POST['ulTransferId']]->progress=1;
  260.                     // Save result in uploads file
  261.                     tWritePHPTransfersFile($transfersArray);
  262.                 }
  263.                 // Move uploaded file (unexpected) failure
  264.                 displayUploadCompletedPage(false,cfCaption('explorerErrorFileSend2').' (cannot move uploaded file)');
  265.             }
  266.         }
  267.     }
  268.  
  269.     // Display upload completed page
  270.     displayUploadCompletedPage($uploadFile);
  271. }
  272.  
  273. /**
  274.  * @desc Display upload progress bar
  275.  *         This page is called within an iframe of main upload page
  276.  *
  277.  */
  278. function uploadProgressBar(){
  279.     /**
  280.      * Display page
  281.      */
  282.     if(isset($_GET['transferId']) && !isset($_POST['asyncRequest'])){
  283.         $transferId=$_GET['transferId'];
  284.         cfInsertHEAD(false);
  285. ?>
  286. <body onload="updateProgressBar('<?php echo $transferId; ?>',0,100)" style="margin:0;padding:0">
  287. <script type="text/javascript">
  288. function updateProgressBar(transferId,perc,nr){
  289.     progressSetPerc('uploadProgressBar',perc);
  290.     progressSetText('uploadProgressBar',Math.floor(perc)+'%');
  291.     window.setTimeout('sendData("transferId='+transferId+'&progressBar=1","upload.php")',nr);
  292. }
  293. function cancelUpload(){
  294.     parent.document.stop();
  295. }
  296. </script>
  297.  
  298. <center id="center">
  299. <?php
  300.         // Insert progress bar
  301.         echo outProgressBar(0,'95%','0%','uploadProgressBar',false,false,'margin:0');
  302.         echo '</center></body>';
  303.     }
  304.  
  305.     /**
  306.      * Async refresh
  307.      */
  308.     else{
  309.         $updateInterval=1;
  310.         $progress=0;
  311.  
  312.         $transferId=$_POST['transferId'];
  313.         cfAsyncHeader();
  314.         /**
  315.          * Upload progress
  316.          */
  317.         //if(function_exists('apc_fetch')) $status=apc_fetch('upload_'.$transferId); // Using APC
  318.         //elseif(function_exists('uploadprogress_get_info')) $status=uploadprogress_get_info($transferId); // Using uploadprogress
  319.         if(function_exists('customUploadMonitor')) $status=customUploadMonitor($transferId); // Using uploadprogress
  320.         else $status=false;
  321. //cfDbg($_POST+array($transferId=>$status),1);
  322.  
  323.         if($status){
  324.             // Convert from customProgressMonitor format to APC format
  325.             if(isset($status['transfered'])) $status['current']=$status['transfered'];
  326.  
  327.             // Convert from uploadprogress format to APC format
  328.             if(isset($status['bytes_total'])) $status['total']=$status['bytes_total'];
  329.             if(isset($status['bytes_uploaded'])) $status['current']=$status['bytes_uploaded'];
  330.  
  331.             // Check if upload is not > to max upload size
  332.             if(isset($status['total']) && $status['total'] > cfGGetVar('uploadMaxFilesize')*1024*1024){
  333.                 echo cfAsyncXMLJSaction('dgi("center").innerHTML="'.cfCaptionJS('configUploadMax').cfCaptionJS('genSeparator').cfGGetVar('uploadMaxFilesize').' '.cfCaptionJS('genSizeMb').'"; cancelUpload()');
  334.             }
  335.  
  336.             // Load transers
  337.             require_once(INCLUDE_DIR.'transferFunctions.php');
  338.             $transfers=tReadTransfersFiles();
  339.  
  340.             // Update transfer progress
  341.             if(isset($transfers[$transferId])){
  342.                 $tr=new transfer('upload');
  343.                 $tr=$transfers[$transferId];
  344.                 // Progressive update interval increase
  345.                 if($tr->updateInterval<0.2) $tr->updateInterval+=0.01;
  346.                 elseif($tr->updateInterval<1) $tr->updateInterval+=0.1;
  347.                 elseif($tr->updateInterval<3) $tr->updateInterval+=1;
  348.                 $updateInterval=$tr->updateInterval;
  349.                 // Update progress
  350.                 if(isset($status['current']) && isset($status['total']) && $status['total']>0) {
  351.                     $progress=$tr->updateProgress($status['current']/$status['total'],false);
  352.                 }
  353.                 // Save to file
  354.                 $tr->commitToFile($transfers);
  355.             }
  356.         }
  357.         // Update HTML progress bar
  358.         echo cfAsyncXMLJSaction('updateProgressBar("'.$transferId.'",'.(100*$progress).','.(1000*$updateInterval).')');
  359.         echo cfAsyncFooter();
  360.     }
  361.     exit;
  362. }
  363.  
  364. $transfersArray=array();
  365. $errorMessage=false;
  366.  
  367. /*
  368.  ***************************************************************************************************************************
  369.  * Close-on-upload completed toggle
  370.  ***************************************************************************************************************************
  371.  */
  372. if(isset($_POST['toggleTransferCloseOnCompleted'])) {
  373.     cfRSetVar('transferCloseOnCompleted',(($_POST['toggleTransferCloseOnCompleted']=='true')?true:false));
  374.     exit;
  375. }
  376.  
  377. /*
  378.  ***************************************************************************************************************************
  379.  * Upload progress page
  380.  ***************************************************************************************************************************
  381.  */
  382. if((isset($_GET['progressBar']) && isset($_GET['transferId'])) || (isset($_POST['progressBar']) && isset($_POST['transferId']))) uploadProgressBar();
  383.  
  384. /*
  385.  ***************************************************************************************************************************
  386.  * Pre-Upload processing
  387.  ***************************************************************************************************************************
  388.  */
  389. if(!count($_FILES) && isset($_POST['preUlFile']) && isset($_POST['preUlDir'])) {
  390.     // If resource sets an extension filter, verify that file matches
  391.     if(cfRGetVar('extensionFilter') && !in_array(cfFileExtension(cfUTF8Decode($_POST['preUlFile'])),cfRGetVar('extensionFilter'))) displayUploadCompletedPage(false,cfCaption('explorerFormatError').' (ext not allowed)');
  392.  
  393.     // If resource sets an file type filter, verify that file matches
  394.     if(cfRGetVar('fileTypeFilter') && !in_array(efFileType(cfUTF8Decode($_POST['preUlFile'])),cfRGetVar('fileTypeFilter'))) displayUploadCompletedPage(false,cfCaption('explorerFormatError').' (type not allowed)');
  395.  
  396.     // If file not yet sent : display "upload in progress" page and launch upload
  397.     displayUploadInProgressPage();
  398. }
  399.  
  400.  
  401. /*
  402.  ***************************************************************************************************************************
  403.  * Process completed download
  404.  ***************************************************************************************************************************
  405.  */
  406.  
  407. // If missing POST parameters, display error message
  408. if(!isset($_POST['ulDir']) || !isset($_POST['ulTransferId'])) {
  409.     displayUploadCompletedPage(false,cfCaption('genError').'<br/>'.cfCaption('configUploadMax').cfCaption('genSeparator').cfGGetVar('uploadMaxFilesize').' '.cfCaption('genSizeMb'));
  410. }
  411.  
  412. // Check passed file has been uploaded
  413. if($_FILES['ulInput']['error']) displayUploadCompletedPage(false,cfCaption('explorerFormatError').' (err:'.$_FILES['ulInput']['error'].')');
  414. if(empty($_FILES['ulInput']['tmp_name'])) displayUploadCompletedPage(false,cfCaption('explorerFormatError').' (empty tmp_name)');
  415. if(!is_uploaded_file($_FILES['ulInput']['tmp_name'])) displayUploadCompletedPage(false,cfCaption('explorerFormatError').' (!is_uploaded_file)');
  416.  
  417. // Verify that transfer is present in upload.txt file and that it has not been stopped (except for frameless upload where transfer is not logged)
  418. if(cfRGetVar('trackTransfers')){
  419.     $transfersArray=tReadTransfersFiles();
  420.     if(!isset($transfersArray[$_POST['ulTransferId']]) || $transfersArray[$_POST['ulTransferId']]->status!=3) displayUploadCompletedPage(false,cfCaption('transfersCanceled').' (canceled)');
  421. }
  422.  
  423.  
  424. // Process uploaded file
  425. if(function_exists('processUploadedFile')) processUploadedFile();
  426. else uploadProcessUploadedFile();
  427. ?>